# D:\dazuoye\app\views\task4_predict.py

from flask import Blueprint, jsonify
from app.data_loader import prediction_data, campaign_data  # campaign_data保留，用于另一个接口
import pandas as pd
from scipy.optimize import linprog

# 移除所有绘图相关的库
# import matplotlib.pyplot as plt
# import seaborn as sns
# import os
# import uuid
# from flask import current_app, url_for

task4_bp = Blueprint('task4_predict', __name__)


@task4_bp.route('/api/marketing/demand_forecast', methods=['GET'])
def get_demand_forecast():
    """【方案A-最终版】API: 直接返回已有的需求预测数据 (JSON)"""
    if prediction_data is None:
        return jsonify({"error": "需求预测数据未能加载"}), 500

    try:
        df = prediction_data.copy()

        # 1. 数据处理
        df['时期'] = pd.to_datetime(df['时期'])
        df['ci_value'] = df['置信区间'].str.extract(r'(\d+)').astype(float)
        df['lower_bound'] = df['预测需求'] - df['ci_value']
        df['upper_bound'] = df['预测需求'] + df['ci_value']

        # 2. 构建结构化的JSON返回结果
        # 最终格式为: {"PF-1001": {"dates": [...], "forecast": [...]}, "PF-1002": {...}}
        result = {}
        # 按产品ID分组，为每个产品生成一条时间序列数据
        for product_id, group in df.groupby('产品ID'):
            # 按时间排序
            group = group.sort_values('时期')
            result[product_id] = {
                "dates": group['时期'].dt.strftime('%Y-%m-%d').tolist(),
                "forecast": group['预测需求'].tolist(),
                "lower_bound": group['lower_bound'].tolist(),
                "upper_bound": group['upper_bound'].tolist()
            }

        return jsonify(result)

    except Exception as e:
        return jsonify({"error": f"处理预测数据时出错: {e}"}), 500


# (budget_optimization 接口保持不变)
@task4_bp.route('/api/marketing/budget_optimization', methods=['GET'])
def get_budget_optimization():
    if campaign_data is None:
        return jsonify({"error": "营销活动数据未能加载"}), 500
    try:
        total_spent_before = campaign_data['已花费'].sum()
        if total_spent_before == 0:
            original_roi = 0
        else:
            total_return_before = (campaign_data['已花费'] * campaign_data['投资回报率(ROI)']).sum()
            original_roi = total_return_before / total_spent_before

        channel_roi = campaign_data.groupby('渠道')['投资回报率(ROI)'].mean()
        c = -channel_roi.values
        total_budget = campaign_data['总预算'].sum()
        A_ub = [[1] * len(channel_roi)]
        b_ub = [total_budget]
        bounds = [(0, None) for _ in channel_roi]
        res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs')

        if res.success and res.x.sum() > 0:
            optimized_roi = -res.fun / res.x.sum()
        else:
            optimized_roi = original_roi

        return jsonify({
            "labels": ["优化前", "优化后"],
            "roi_values": [original_roi, optimized_roi]
        })
    except Exception as e:
        return jsonify({"error": f"计算预算优化时出错: {e}"}), 500